package m4d1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

//文件上传客户端
public class fTCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(1234);


        //服务器一值处于监听状态，客户端就不用关闭了
        while (true) {


            //获取客户端对象
            Socket socket = serverSocket.accept();

            //多线程提高程序效率
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        //获取网络字节输入流
                        InputStream is = socket.getInputStream();

                        //判断文件加存在
                        File file = new File("day02\\src\\m4d1");
                        if (!file.exists()) {
                            file.mkdir();
                        }


                        //自定义文件名   域名+毫秒值+随机数
                        String filename = "g" + System.currentTimeMillis() + new Random().nextInt(9999999) + ".txt";


                        //创建本地字节输入流，绑定目的地
                        FileOutputStream fos = new FileOutputStream(file + "\\" + filename);

                        //网络字节输出流读取客户端的文件
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len = is.read(bytes)) != -1) {
                            //本地字节输出流保存文件到服务器
                            fos.write(bytes, 0, len);
                        }

                        //创建网络字节输出流，并用此回写客户端
                        socket.getOutputStream().write("上传成功".getBytes());

                        fos.close();
                        socket.close();
                    }catch(IOException e){
                        System.out.println(e);
                    }
                }
            }).start();


        }

//       serverSocket.close();  客户端不关闭了
    }
}
